package com.cinnamon.rss.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.cinnamon.rss.logic.RSSFeedParser;
import com.cinnamon.rss.model.Feed;
import com.cinnamon.rss.model.Item;
import com.cinnamon.rss.model.User;
import com.cinnamon.rss.repository.FeedRepository;
import com.cinnamon.rss.repository.UserRepository;

@Service("scheduleService")
public class ScheduleService {

		@Autowired
		UserRepository userRepo;
	
		@Autowired
		FeedRepository feedRepo;
		
		// update each 15 seconds
		@Scheduled(fixedRate=15000) 
		public void updateAll() {
			
			List<User> users = userRepo.findAll();	
			
			for(User u : users) {
				for(Feed f : feedRepo.findByUser(u)) {
					update(f);
				}
			}	
			
		}
		
		public void update(Feed feed) {
				Feed temp_feed = null;
				
				temp_feed = (new RSSFeedParser(feed.getRssSourceLink())).readFeed();
				
				List<Item> old_items = feed.getItems();
				List<Item> new_items = temp_feed.getItems();
								
				//	look over new_items, and add new items to old_items
				for(int i = 0; i < new_items.size(); i++) {
					Item item = (Item) new_items.get(i);
					if(!old_items.contains(item)) {
						old_items.add(item);
					}
				}
				
				feedRepo.save(feed);
		}
	
}
